/*
 * Copyright 2010 - 2011, The PLDesktop Development Team
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 */

#include "initrd.h"

#include <string.h>
#include <machine/pc/processor/processor.h>
#include <PLJava.h>

InitRD::InitRD(Tar *initrdArchive) : m_initrdArchive(initrdArchive) {
    TarFile *f = initrdArchive->file("/initrd/etc/startup.ini");
    if(f && strcmp(f->filename(), "startup.ini") == 0) {
        m_ini = new IniReader(f);
        m_ini->setActivePart("Information");
        printf("Version %s/%s", m_ini->getValue("Architecture"), m_ini->getValue("Version"));
        printf(" (%s [rev:%s])\n", m_ini->getValue("BuildDate"), m_ini->getValue("Revision"));
        printf("Booting");
    } else {
        printIniReadingError("File not found.");
    }
}

void InitRD::loadModules() {
    m_ini->setActivePart("Base Modules");
    const char *pitModule = m_ini->getValue("Programmable Interval Timer");
    TarFile *pit = m_initrdArchive->file(pitModule);
    if(isClass(pit->filename())) {
        PLJava::instance().startJavaFile(pit->startPosition());
    } else {
        if(pit->type() == TarHeader::NormalFile) {
            InitRDModuleInfo *module = m_moduleHandler.loadModule(pit);
            PLUNUSED(module);
        } else {
            printModuleLoadingError(pitModule);
        }
    }
}

void InitRD::printModuleLoadingError(const char *module) {
    printf("\nError loading base system Module: %s", module);
    printf("System halted!");
    PLProcessor::instance().halt();
}

void InitRD::printIniReadingError(const char *message) {
    printf("\nError reading startup.ini file: %s", message);
    printf("System halted!");
    PLProcessor::instance().halt();
}

bool InitRD::isClass(const char *fileName) {
    int strLen = strlen(fileName);
    if(strLen > 6) {
        const char *file = fileName + strLen - 5;
        if(strcmp(file, "class") == 0) {
            return true;
        }
    }
    return false;
}
